package com.zr0726.news.web.admin;

import com.zr0726.news.po.GiteeRequest;
import com.zr0726.news.po.GiteeUser;
import com.zr0726.news.po.User;
import com.zr0726.news.service.UserService;
import com.zr0726.news.service.impl.GiteeUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private GiteeUserServiceImpl gitee;
    @Value("${gitee.client_id}")
    private String client_id;
    @Value("${gitee.accessToken.redirect_uri}")
    private String redirect_uri;
    @Value("${gitee.accessToken.client_secret}")
    private String client_secret;


    @GetMapping
    public String loginPage(){
        return "admin/login";
    }

    @PostMapping("/admin/login")
    public String login(@RequestParam String username, @RequestParam String password,
                        HttpSession session, RedirectAttributes attributes , Model model){
        User user = userService.checkUsers(username,password);
        if(user!=null){
            user.setPassword(null);
            session.setAttribute("user",user);
            model.addAttribute("username",user.getUsername());
            return "afterlogin";
        }else {
            attributes.addFlashAttribute("message","用户名或密码错误");
            return "loginfail";
        }
    }

    @GetMapping("/admin/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/admin";
    }
    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,Model model) {
        GiteeRequest accessToken = new GiteeRequest();
        accessToken.setCode(code);
        accessToken.setClient_id(client_id);
        accessToken.setRedirect_uri(redirect_uri);
        accessToken.setClient_secret(client_secret);
        String access = gitee.getAccess(accessToken);
        GiteeUser giteeUser =  gitee.getGiteeUser(access);
        System.out.println(giteeUser.getId());
        User user = userService.checkUsers(giteeUser.getId());
        if(user!=null){
            user.setPassword(null);
            // session.setAttribute("user",user);
            model.addAttribute("username",user.getUsername());
            return "afterlogin";
        }else {
            //attributes.addFlashAttribute("message","用户名或密码错误");
            return "loginfail";
        }
    }
}
